import { login, logout, getInfo, addmerchant, addshop } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_CARDNAME: (state, cardname) => {
    state.cardname = cardname
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { phone, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: phone.trim(), validate: password }).then(response => {
        // const { result } = response

        resolve(response)
      }).catch(error => {
        console.log('success ok login d' + error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { result } = response

        if (!result) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction, cardname } = result

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        if (result.signpic)
          sessionStorage.setItem('signpic', result.signpic)
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_CARDNAME', cardname)
        resolve(result)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    console.log('token:'+state.token)
    console.log( state.token)

    return new Promise((resolve, reject) => {
      logout().then(() => {
        console.log('okoka')

        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        console.log('okokb')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  // user login
  addmerchant({ commit }, merchant) {
    return new Promise((resolve, reject) => {
      addmerchant(merchant).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user login
  addshop({ commit }, shop) {
    return new Promise((resolve, reject) => {
      addshop(shop).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
    // user login
    // updateshop({ commit }, shopinfo) {
    //   const { phone, password } = shopinfo
    //   return new Promise((resolve, reject) => {
    //     login({ phone: phone.trim(), validate: password }).then(response => {
    //       // const { result } = response
    //       console.log('success ok login a')
    //       commit('SET_TOKEN', response.result)
    //       console.log('success ok login b')
    //       setToken(response.result)
    //       // token保存到cookie里。
    //       console.log('success ok login c')
    //       resolve()
    //     }).catch(error => {
    //       console.log('success ok login d' + error)
    //       reject(error)
    //     })
    //   })
    // },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
